package com.cloud.manager.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.manager.web.domain.App;
import com.cloud.manager.web.domain.AppInfo;
import com.cloud.manager.web.domain.Version;
import com.cloud.manager.web.mapper.VersionMapper;
import com.cloud.manager.web.service.AppService;
import com.cloud.manager.web.mapper.AppMapper;
import com.cloud.manager.web.service.VersionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author FineEx
 * @description 针对表【tb_app】的数据库操作Service实现
 * @createDate 2021-11-30 18:02:27
 */
@Service
public class AppServiceImpl extends ServiceImpl<AppMapper, App>
        implements AppService {

    @Resource
    AppMapper appMapper;
    @Resource
    VersionService versionService;
    @Resource
    PlatformTransactionManager transactionManager;

    @Override
    public List<App> selectAllApp() {
        return appMapper.selectList(null);
    }

    @Override
    public void addApp(AppInfo info) {
        QueryWrapper<App> wrapper = new QueryWrapper<>();
        wrapper.eq("packageName", info.getApp().getPackageName());
        App app = appMapper.selectOne(wrapper);
        boolean isExist = app != null;
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.execute(txStatus -> {
            long appId;
            if (isExist) {
                appMapper.updateById(app);
                appId = app.getAppId();
            } else {
                appMapper.insert(info.getApp());
                appId = appMapper.selectOne(wrapper).getAppId();
            }
            info.getVersion().setAppId(appId);
            versionService.addVersion(info.getVersion());
            return null;
        });
    }
}




